import { fetchModels } from '@/api/face'

const FACE_RECOGNITION_MODELS_ID = 1
const SELECTED_FACE_RECOGNITION_MODEL_LABEL = 'SELECTED_FACE_RECOGNITION_MODEL_LABEL'
const SELECTED_FACE_RECOGNITION_MODEL_VALUE = 'SELECTED_FACE_RECOGNITION_MODEL_VALUE'
const TURN_ON_ANTI_SPOOFING = 'TURN_ON_ANTI_SPOOFING'

const state = () => ({
  faceRecognitionModels: [],
  selectedFaceRecognitionModelLabel: '',
  selectedFaceRecognitionModelValue: 0,
  turnOnAntiSpoofing: false,
  antiSpoofingModels: [],
  selectedAntiSpoofingModelLabel: '',
  selectedAntiSpoofingModelValue: 0
})

const getters = {
}

const actions = {
  getAllFaceRecognitionModels({ commit }) {
    fetchModels(FACE_RECOGNITION_MODELS_ID).then(res => {
      if (res.data) {
        commit('setFaceRecognitionModels', res.data)
      }
    })
  },
  getSelectedFaceRecognitionModel({ commit }) {
    const modelLabel = window.localStorage.getItem(SELECTED_FACE_RECOGNITION_MODEL_LABEL)
    const modelValue = window.localStorage.getItem(SELECTED_FACE_RECOGNITION_MODEL_VALUE)
    if (modelLabel && modelValue) {
      commit('setSelectedFaceRecognitionModel', {
        modelLabel: modelLabel,
        modelValue: modelValue
      })
    } else {
      commit('setSelectedFaceRecognitionModel', {
        modelLabel: 'FaceNet',
        modelValue: 1
      })
    }
  },
  getTurnOnAntiSpoofing({ commit }) {
    const turnOnAntiSpoofing = window.localStorage.getItem(TURN_ON_ANTI_SPOOFING)
    if (turnOnAntiSpoofing === 'true') {
      commit('setTurnOnAntiSpoofing')
    }
  },
  getSelectedAntiSpoofingModel({ commit }) {
    const selectedAntiSpoofingModel = window.localStorage.getItem('SELECTED_ANTI_SPOOFING_MODEL')
    if (selectedAntiSpoofingModel) {
      return selectedAntiSpoofingModel
    } else {
      return ''
    }
  },
  changeSelectedFaceRecognitionModel({ state, commit }, value) {
    const faceRecognitionModel = state.faceRecognitionModels.find(item => item.value === value)
    commit('setSelectedFaceRecognitionModel', {
      modelLabel: faceRecognitionModel.label,
      modelValue: faceRecognitionModel.value
    })
  },
  toggleTurnOnAntiSpoofing({ commit }) {
    commit('setTurnOnAntiSpoofing')
  }
}

const mutations = {
  setFaceRecognitionModels(state, faceRecognitionModels) {
    state.faceRecognitionModels = faceRecognitionModels
  },
  setSelectedFaceRecognitionModel(state, { modelLabel, modelValue }) {
    state.selectedFaceRecognitionModelLabel = modelLabel
    state.selectedFaceRecognitionModelValue = modelValue
    window.localStorage.setItem(SELECTED_FACE_RECOGNITION_MODEL_LABEL, modelLabel)
    window.localStorage.setItem(SELECTED_FACE_RECOGNITION_MODEL_VALUE, modelValue)
  },
  setTurnOnAntiSpoofing(state) {
    state.turnOnAntiSpoofing = !state.turnOnAntiSpoofing
    window.localStorage.setItem(TURN_ON_ANTI_SPOOFING, state.turnOnAntiSpoofing)
  }
}

export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations
}
